var util = require('util');
var oauth = require('node-oauth');
var config = require('../config');

var models = require('../models');
var Session = models.Session;

var api = config.api;

function consumer() {
    return new oauth.OAuth(api.requestToken, api.accessToken, config.consumerKey, config.consumerSecret, '1.0', api.authorizeCallback, 'HMAC-SHA1');
}

module.exports = function(app) {
    app.get('/authorize/connect', function(req, res, next) {
        consumer().getOAuthRequestToken(function(err, oauthToken, oauthTokenSecret, json) {
            if (err) {
                res.send('Error getting OAuth request token: ' + util.inspect(err), 500);
            } else {
                req.session.oauthRequestToken = oauthToken;
                req.session.oauthRequestTokenSecret = oauthTokenSecret;
                res.redirect(api.authorize + '?oauth_token=' + oauthToken);
            }
        });
    });

    app.get('/authorize/callback', function(req, res, next) {
        consumer().getOAuthAccessToken(req.session.oauthRequestToken, req.session.oauthRequestTokenSecret, req.query.oauth_verifier, function(err, oauthAccessToken, oauthAccessTokenSecret, json) {
            if (err) {
                res.send('Error getting OAuth access token: ' + util.inspect(err) + '[' + oauthAccessToken + '][' + oauthAccessTokenSecret + '][' + util.inspect(json) + ']', 500);
            } else {
                var screenName = json.screen_name;
                req.session.oauthAccessToken = oauthAccessToken;
                req.session.oauthAccessTokenSecret = oauthAccessTokenSecret;
                req.session.screenName = screenName;
                Session.update({
                    screenName: screenName
                }, {
                    $set: {
                        screenName: screenName,
                        oauthAccessToken: oauthAccessToken,
                        oauthAccessTokenSecret: oauthAccessTokenSecret
                    }
                }, {
                    upsert: true
                }, function(err) {
                    if (err) {
                        res.send('Error saving OAuth access token, screenName: ' + screenName, 500);
                    } else {
                        res.send('You are signed in: ' + req.session.screenName);
                    }
                });
            }
        });
    });
};

